package academic.ui.client.widgets;

import java.util.Date;

import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Composite;

import ui.client.GenericContainerTag;

public class TimerDiv extends Composite {

	Date endDate;
	private GenericContainerTag div = new GenericContainerTag("div");
	private GenericContainerTag timerAmt = new GenericContainerTag("div");

	public TimerDiv(Date d) {
		endDate=d;
		GenericContainerTag timerDiv = new GenericContainerTag("div");
		timerDiv.setStyleName("timerDiv");
		GenericContainerTag timeLbl = new GenericContainerTag("div","Time Left");
		timerDiv.add(timeLbl);
		timeLbl.setStyleName("timeLeft");
		timerDiv.add(timerAmt);
		Timer t = new Timer() {

			@Override
			public void run() {
				updateTimerAmt();
			}
			
		};
		t.scheduleRepeating(1000);
		
		div.setStyleName("absolute");
		GenericContainerTag slideTimerDiv = new GenericContainerTag("div");
		slideTimerDiv.setStyleName("relative");
		div.add(slideTimerDiv);
		slideTimerDiv.add(timerDiv);
		initWidget(div);
	}
	
	
	protected void updateTimerAmt() {
		long milliseconds1 = new Date().getTime();
		long milliseconds2 = endDate.getTime();
		long time = milliseconds2 - milliseconds1;
		if(time>=0) {
			long seconds = time/1000;
			long minutes = time/(60 * 1000);
			long hours = time/(60*60*1000);
			long days = time/(24*60*60*1000);
			String timeLeftMsg = "";
			if(days>=1)
				timeLeftMsg+=days+(days>1?" days ":" day ");
			long actualHours = hours-(days*24);
			long actualMinutes = minutes-(hours*60);
			timeLeftMsg+=((hours>0 && actualHours>0)?actualHours+(actualHours>1?" hours ":" hour "):" ");
			timeLeftMsg+=((minutes>0 && actualMinutes>0)?actualMinutes+(actualMinutes>1?" minutes ":" minute "):" ");
			if(days<1)
				timeLeftMsg+=NumberFormat.getFormat("##00").format(seconds-(minutes*60))+" seconds";
			timerAmt.getElement().setInnerHTML(timeLeftMsg);
		}
	}
}
